const bg = chrome.extension.getBackgroundPage()

var tokenRes
// 初始模板内容
var infoList = [
  { title: `1.相关模块接口对接\n2.部分bug修改\n3.需求沟通并且重构部分逻辑`, disabled: true }
]
// 当前选中模板
var checkInfoIdx = 0
// 模板列表字符串
var htmlStr = ``
var weekTime
chrome.storage.sync.get(['psw', 'usr', 'infoArr', 'checkInfoIdx', 'weekTime', 'num', 'ids'], async function (result) {
  console.log(result)
  let { usr, psw, infoArr, num, ids } = result
  if (infoArr) infoList = infoArr
  else chrome.storage.sync.set({ infoArr: infoList })
  if (result.checkInfoIdx) checkInfoIdx = result.checkInfoIdx
  else chrome.storage.sync.set({ checkInfoIdx })
  if (!psw) {
    psw = '123456'
    chrome.storage.sync.set({ psw })
  }
  if (!num) chrome.storage.sync.set({ num: -1 })
  if (!Array.isArray(ids)) chrome.storage.sync.set({ ids: [] })
  if (!result.weekTime) {
    weekTime = '16:00'
    chrome.storage.sync.set({ weekTime })
  } else {
    weekTime = result.weekTime
  }

  if (usr && psw) init(usr, psw)

  $("#count").html(checkInfoIdx + 1)
  $("#psw").val(psw)
  $("#weekTime").val(weekTime)
  $("#usr").val(usr)
  loader()
})

$("#selectProject").click(async function () {
  chrome.storage.sync.get(['usr', 'psw'], res => {
    let { usr, psw } = res
    if (!usr || !psw) {
      alert('账号密码填写完整！')
      return
    }
    init(usr, psw)
  })
})

async function init (usr, psw) {
  tokenRes = await bg.getToken({ loginName: usr, passWord: psw })
  if (!tokenRes.status) bg.msg(tokenRes.message)
  // await bg.bToken(cb => {
  //   cb()
  // })
  bg.baseToken = tokenRes.data.uuid
  chrome.storage.sync.set({ userId: tokenRes.data.userId, baseToken: tokenRes.data.uuid })
  await loaderProject()
}
async function loaderProject () {
  await setPorject(tokenRes.data.userId)
  let ids = await bg.getDayId(tokenRes.data.userId)
  chrome.storage.sync.set({ ids })
}

// 第几个项目
$("#num").change(function () {
  let num = $(this).val()
  chrome.storage.sync.set({ num })
})
$("#weekTime").change(function () {
  let weekTime = $(this).val()
  let arr = weekTime.split(':')
  bg.maxTimer()
  if (arr[0] == 16 || arr[0] == 17) {
    if (arr[0] == 17 && arr[1] > 30) {
      alert('只能填16:00~17:30之内的时间')
      weekTime = '16:00'
      $(this).val(weekTime)
      chrome.storage.sync.set({ weekTime })
      return
    }
  } else {
    alert('只能填16:00~17:30之内的时间')
    weekTime = '16:00'
    $(this).val(weekTime)
    chrome.storage.sync.set({ weekTime })
    return
  }
  weekTime = $(this).val()
  chrome.storage.sync.set({ weekTime })
  console.log(weekTime)
})
// 每个textarea失焦
$(".infoBox").on('blur', '.area', function () {
  if (!$(this).val()) return
  let idx = $(this).parent().index()
  infoList[idx].title = $(this).val()
  chrome.storage.sync.set({ infoArr: infoList })
})
$("#usr").blur(function () {
  chrome.storage.sync.set({ usr: $(this).val() })
})
$("#psw").blur(function () {
  chrome.storage.sync.set({ psw: $(this).val() })
})


// 添加按钮
$("#add").click(function () {
  infoList.push({ title: '', disabled: false })
  loader()
})



// 删除按钮
$(".infoBox").on('click', '.del', function () {
  let idx = $(this).parent().index()
  if (idx == checkInfoIdx) {
    $(`.infoBox>li`).removeClass('checked')
    $(`.infoBox>li:eq(0)`).addClass('checked')
    chrome.storage.sync.set({ checkInfoIdx: 0 })
    checkInfoIdx = 0
    $("#count").html(checkInfoIdx + 1)
  } else if (idx < checkInfoIdx) {
    $(`.infoBox>li`).removeClass('checked')
    $(`.infoBox>li:eq(0)`).addClass('checked')
    checkInfoIdx -= 1
    chrome.storage.sync.set({ checkInfoIdx })

    $("#count").html(checkInfoIdx + 1)
  }
  infoList.splice(idx, 1)
  chrome.storage.sync.set({ infoArr: infoList })
  loader()
})

// 选中按钮
$(".infoBox").on('click', '.checkBtn', function () {
  let idx = $(this).parent().index()
  if ($(`#text${idx}`).val().length < 15) {
    alert('不能选择不大于15个字的模板')
    return
  }
  $(`.infoBox>li`).removeClass('checked')
  $(`.infoBox>li:eq(${idx})`).addClass('checked')
  checkInfoIdx = idx
  chrome.storage.sync.set({ checkInfoIdx })
  $("#count").html(checkInfoIdx + 1)
})
// 使用说明
$("#readMe").click(function () {
  window.open('https://ddll.top/#/index/articleDetail?id=186')
})

function setPorject (userId) {
  bg.db('https://www.sgwl.com:4431/sgoa/project/queryByUserId', 'post', { userId }).then(res => {
    console.log(res)
    $('#num').html('')
    chrome.storage.sync.get(['num'], function (result) {
      res.data.forEach(v => {
        $('#num').append(new Option(v.name, v.id))
      })
      if (result.num) {
        $("#num").val(result.num)
        chrome.storage.sync.set({ num: result.num })
      }
    })
  })
}



// 立即执行按钮
$("#action").click(async function () {
  if (!$("#usr").val() || !$("#psw").val()) {
    alert('账号密码填写完整！')
    return
  }
  let ids = await bg.getDayId(tokenRes.data.userId)
  chrome.storage.sync.set({ ids })
  if (new Date().getHours() >= 16) {
    if (ids.length) bg.update()
    else bg.insert()
  } else {
    if (confirm('还没到报工填写时间，是否仍要执行？')) {
      if (ids.length) bg.update()
      else bg.insert()
    }
  }
})

function loader () {
  htmlStr = ''
  infoList.forEach((v, i) => {
    htmlStr += `
    <li>
      <textarea class="area" id="text${i}" cols="30" ${v.disabled ? 'disabled' : ''} rows="4">${v.title}</textarea>
      <button class="checkBtn">选择</button>
      ${v.disabled ? "<button disabled class='moren'>默认</button>" : '<button class="del">删除</button>'}
    </li>
    `
  })
  $(".infoBox").html(htmlStr)
  $(`.infoBox>li`).removeClass('checked')
  $(`.infoBox>li:eq(${checkInfoIdx})`).addClass('checked')
}
